﻿using MvvmCross.Core.ViewModels;
using Sidvall.AuthorizationManager.UI.Entities;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Sidvall.AuthorizationManager.UI.ViewModels
{
	public class FilterViewModel : Sidvall.IdentityManager.UI.ViewModels.PluginViewModelBase
	{
		#region Public Members

		#region AuthorizationScopes

		private AuthorizationScopeCollection _AuthorizationScopes;
		public AuthorizationScopeCollection AuthorizationScopes
		{
			get
			{
				return _AuthorizationScopes;
			}
			private set
			{
				_AuthorizationScopes = value;
				RaisePropertyChanged("AuthorizationScopes");
			}
		}

		#endregion
		#region FilterContext

		private FilterContext _FilterContext;
		public FilterContext FilterContext
		{
			get
			{
				if (_FilterContext == null)
					this.FilterContext = new FilterContext();
				return _FilterContext;
			}
			private set
			{
				if (_FilterContext != null)
					_FilterContext.PropertyChanged -= OnFilterContextPropertyChanged;
				_FilterContext = value;
				if (_FilterContext != null)
					_FilterContext.PropertyChanged += OnFilterContextPropertyChanged;
				RaisePropertyChanged("FilterContext");
				RaisePropertyChanged("CanClearAuthorizationScope");
			}
		}

		#endregion
		#region CanClearAuthorizationScope

		public bool CanClearAuthorizationScope
		{
			get
			{
				if (this.FilterContext.AuthorizationScopeId == null)
					return false;
				return true;
			}
		}

		#endregion

		// Commands
		#region ClearAuthorizationScopeCommand

		public ICommand ClearAuthorizationScopeCommand
		{
			get
			{
				return new MvxCommand(ClearAuthorizationScope);
			}
		}

		#endregion
		#region ClearAuthorizationScope

		public void ClearAuthorizationScope()
		{
			this.FilterContext.AuthorizationScopeId = null;
		}

		#endregion

		#region StartAsync

		protected override async Task StartAsync()
		{
			this.AuthorizationScopes = await Sidvall.AuthorizationManager.UI.SystemContext.Current.DataPortal.AuthorizationScopeManager.GetItemsAsync();
		}

		#endregion

		#endregion
		#region Private Members

		#region OnFilterContextPropertyChanged

		private void OnFilterContextPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			RaisePropertyChanged("CanClearAuthorizationScope");
			OnPluginMessage(this.FilterContext.Serialize());
		}

		#endregion

		#endregion
	}
}
